package com.chazz.tools;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.util.DruidDataSourceUtils;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;

public class ConnectionPools {
    static Properties properties = new Properties();
    static DataSource dataSource = null;
    private static ConnectionPools instace = null;
    private Connection connection = null;

    // 静态代码块初始化加载驱动
    static {

        try {
            // 通过类加载器来获得流
            InputStream in = DruidDataSourceUtils.class.getResourceAsStream("/db.properties");
            // 通过流读取配置文件中的内容到集合中
            properties.load(in);
            //通过Druid工厂加载文件注册驱动，初始化连接池
            dataSource = loadDataSource();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //构造方法私有化
    private ConnectionPools() {

    }

    /**
     * 单例模式确保只返回一个连接对象
     *
     * @return
     */
    public static ConnectionPools getInstace() {
        if (instace == null) {
            synchronized (ConnectionPools.class) {
                if (instace == null) {
                    instace = new ConnectionPools();
                }
            }
        }
        return instace;
    }


    /**
     * 返回一个数据源
     *
     * @return
     */
    public DataSource getDataSource() {
        return dataSource;
    }

    /**
     * 加载数据源
     *
     * @return
     */
    private static DataSource loadDataSource() {
        DataSource source = null;
        try {
            source = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return source;
    }

}
